package cn.maydaymemory.maydaycore.loader;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class LibsLoader {
    public static void loadJars(File dir){
        if(!dir.exists()) return;
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            if(files==null) return;
            for(File file:files) loadJars(file);
        }else{
            loadJar(dir);
        }
    }
    public static void loadJar(File jarFile) {

        if (!jarFile.exists()) return;
        if (jarFile.isDirectory()) return;
        String name = jarFile.getName();
        if(!name.substring(name.lastIndexOf(".")).equals(".jar")) return;

        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        } catch (NoSuchMethodException | SecurityException e1) {
            e1.printStackTrace();
        }

        if(method==null) return;
        boolean accessible = method.isAccessible();

        try {
            if (!accessible) {
                method.setAccessible(true);
            }
            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            java.net.URL url = jarFile.toURI().toURL();

            method.invoke(classLoader, url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //回写访问权限
            method.setAccessible(accessible);
        }
    }
}
